package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountLog;
import cn.wolfcode.domain.AccountTransaction;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountLogMapper;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    @Transactional
    public void reducePoints(OperateIntergralVo op) {
        //插入日志信息
        AccountLog log = new AccountLog();
        log.setAmount(op.getValue());
        log.setType(AccountLog.TYPE_DECR);
        log.setGmtTime(new Date());
        log.setInfo(op.getInfo());
        log.setPkValue(op.getPk());
        accountLogMapper.insert(log);
        //减少积分
        int count = usableIntegralMapper.reducePoints(op.getUserId(),op.getValue());
        if (count==0){
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
    }

    @Override
    public void refundIntergal(OperateIntergralVo op) {
        //插入日志信息
        AccountLog log = new AccountLog();
        log.setAmount(op.getValue());
        log.setType(AccountLog.TYPE_INCR);
        log.setGmtTime(new Date());
        log.setInfo(op.getInfo());
        log.setPkValue(op.getPk());
        accountLogMapper.insert(log);
        //增加积分
        int count = usableIntegralMapper.addIntergral(op.getUserId(),op.getValue());
        if (count==0){
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
    }
}
